/*
 * Copyright (c) 1995, 2008, Oracle and/or its affiliates. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 *   - Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *
 *   - Redistributions in binary form must reproduce the above copyright
 *     notice, this list of conditions and the following disclaimer in the
 *     documentation and/or other materials provided with the distribution.
 *
 *   - Neither the name of Oracle or the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
 * IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */ 

package cluedo.gui;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JDialog;
import javax.swing.JTextField;

import common.DuplicateException;

import cluedo.Player;


import java.beans.*; //property change stuff
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.awt.event.*;

//http://stackoverflow.com/questions/12234850/customize-joptionpane-dialog

/**
 * Gestisce la finestra di dialogo iniziale in cui viene chiesto il nome dell'utente.
 * Ottenuto il nome crea un'istanza di Player e lo registra presso il Registration
 * Server. Se il nome fornito e' gia' in uso, chiede all'utente di inserire un
 * nuovo nome.
 */
class CreatePlayerDialog extends JDialog
                   implements ActionListener,
                              PropertyChangeListener {

	private static final long serialVersionUID = -1665418567361918655L;
	private JFrame aFrame;
    private JTextField textField;
    private JOptionPane optionPane;

    private String btnString1 = "Inizia";
    private String btnString2 = "Annulla";
    
    private String registryHost;
    private CluedoStart cluedoWind;
    private Player myPlayer= null;
    
    /**
     * Visualizza la finestra di dialogo e restituisce il player creato
     * @return il player creato, null se l'operazione e' stata annullata
     */
    public Player showAndGetPlayer() {
    	setLocationRelativeTo(aFrame);
    	setVisible(true);
        return myPlayer;
    }
    
    /** Returns an ImageIcon, or null if the path was invalid. */
    protected static ImageIcon createImageIcon(String path) {
		return new ImageIcon(CreatePlayerDialog.class.getResource(path)); 
    }
    
    /** 
     * Crea la finestra di dialogo. 
     * @param aFrame frame genitore della finestra di dialogo
     * @param registryHost hostname del RMI Registry
     * @param cluedoWind istanza di CluedoStart da usare nella istanziazione di Player
     */
    public CreatePlayerDialog(JFrame aFrame, String registryHost, CluedoStart cluedoWind) {
        super(aFrame, true);
        
        this.aFrame= aFrame;
        this.registryHost= registryHost;
        this.cluedoWind= cluedoWind;
        
        setTitle("The Amazing Cluedo!");

        textField = new JTextField(10);

        //Create an array of the text and components to be displayed.
        String msgString1 = "Inserisci il tuo nome e inizia a giocare:";
        ImageIcon icon = createImageIcon("/img/cluedo.gif");
        
        Object[] array = {icon, msgString1, textField};

        //Create an array specifying the number of dialog buttons
        //and their text.
        Object[] options = {btnString1, btnString2};

        //Create the JOptionPane.
        optionPane = new JOptionPane(array,
                                    JOptionPane.PLAIN_MESSAGE,
                                    JOptionPane.YES_NO_OPTION,
                                    null,
                                    options,
                                    options[0]);
        
        

        //Make this dialog display it.
        setContentPane(optionPane);

        //Handle window closing correctly.
        setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
        addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent we) {
                /*
                 * Instead of directly closing the window,
                 * we're going to change the JOptionPane's
                 * value property.
                 */
                    optionPane.setValue(new Integer(
                                        JOptionPane.CLOSED_OPTION));
            }
        });

        //Ensure the text field always gets the first focus.
        addComponentListener(new ComponentAdapter() {
            public void componentShown(ComponentEvent ce) {
                textField.requestFocusInWindow();
            }
        });

        //Register an event handler that puts the text into the option pane.
        textField.addActionListener(this);

        //Register an event handler that reacts to option pane state changes.
        optionPane.addPropertyChangeListener(this);
    }

    /** This method handles events for the text field. */
    public void actionPerformed(ActionEvent e) {
    	// preme "invio" quando il text field ha il focus
        optionPane.setValue(btnString1);
    }

    /** This method reacts to state changes in the option pane. */
    public void propertyChange(PropertyChangeEvent e) {
        String prop = e.getPropertyName();

        if (isVisible()
         && (e.getSource() == optionPane)
         && (JOptionPane.VALUE_PROPERTY.equals(prop) ||
             JOptionPane.INPUT_VALUE_PROPERTY.equals(prop))) {
            Object value = optionPane.getValue();

            if (value == JOptionPane.UNINITIALIZED_VALUE) {
                //ignore reset
                return;
            }

            //Reset the JOptionPane's value.
            //If you don't do this, then if the user
            //presses the same button next time, no
            //property change event will be fired.
            optionPane.setValue(
                    JOptionPane.UNINITIALIZED_VALUE);

            if (btnString1.equals(value)) {
                String nickname = textField.getText();
                
                if (nickname.equals("")) {
                	JOptionPane.showMessageDialog(
                			this, 
                			"Almeno provaci a scrivere il nome",
        					"Nome non valido",
        					JOptionPane.ERROR_MESSAGE);
                	myPlayer = null;
                    textField.requestFocusInWindow();
    				
                } else if(nickname.compareToIgnoreCase("Io")==0){
                	JOptionPane.showMessageDialog(
                			this,
                			"Il nome \"" + nickname +"\" non puo' essere usato\n" +
                        			"Scegli un altro nome.",
        					"Nome non valido",
        					JOptionPane.ERROR_MESSAGE);
                	myPlayer = null;
                    textField.requestFocusInWindow();
                    
                } else {
                	createPlayer(nickname);
                }
                
            } else { //user closed dialog or clicked cancel
                myPlayer = null;
                clearAndHide();
            }
        }
    }

    private void createPlayer(String nickname) {
    	try {
            myPlayer= new Player(nickname, registryHost, cluedoWind);
            myPlayer.addRegistration();
            // se arrivo qui significa che tutto e' andato a buon fine
            clearAndHide();
        } catch (DuplicateException e1) {
        	JOptionPane.showMessageDialog(
        			this, 
        			"Il nome \"" + nickname + "\" e' gia' presente\n" +
					  "Scegli un altro nome:",
					  "Nome non valido",
					  JOptionPane.ERROR_MESSAGE);
        	myPlayer = null;
            textField.requestFocusInWindow();
            
        } catch (RemoteException e1) {
        	e1.printStackTrace();
        	JOptionPane.showMessageDialog(
        			this, 
        			"Si e' verificato il seguente errore:\n" + e1.getMessage(),
					  "Errore di comunicazione",
					  JOptionPane.ERROR_MESSAGE);
			
		} catch (NotBoundException e1) {
			e1.printStackTrace();
			JOptionPane.showMessageDialog(
        			this, 
        			"Si e' verificato il seguente errore:\n" + e1.getMessage(),
					  "Errore di comunicazione",
					  JOptionPane.ERROR_MESSAGE);
		}
    }
    
    /** This method clears the dialog and hides it. */
    public void clearAndHide() {
        textField.setText(null);
        setVisible(false);
    }
}
